package com.xunyoutest.shop.utils;

import android.content.Context;
import android.media.MediaPlayer;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @describe 音频播放
 * @ideas
 */

public class VoicePlay {
    private ExecutorService mExecutorService;
    private Context mContext;

    private VoicePlay(Context context) {
        this.mContext = context;
        this.mExecutorService = Executors.newCachedThreadPool();
    }

    private volatile static VoicePlay mVoicePlay = null;

    /**
     * 单例
     * @return
     */
    public static VoicePlay with(Context context) {
        if (mVoicePlay == null) {
            synchronized (VoicePlay.class) {
                if (mVoicePlay == null) {
                    mVoicePlay = new VoicePlay(context);
                }
            }
        }
        return mVoicePlay;
    }

    public void play(int raw) {
        mExecutorService.execute(() -> start(raw));
    }
    /**
     * 开始播报
     * @param raw
     */
    private void start(int raw) {
        synchronized (VoicePlay.this) {
            final CountDownLatch mCountDownLatch = new CountDownLatch(1);
            MediaPlayer mediaPlayer = MediaPlayer.create(mContext,raw);
            mediaPlayer.setOnCompletionListener(mediaPlayer1 -> {
                mediaPlayer.reset();
                mediaPlayer.release();
                mCountDownLatch.countDown();
            });
            mediaPlayer.start();

            try {
                mCountDownLatch.await();
                notifyAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
